package com.linux.huhx.concurreny;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Driver2 {
    public static void main(String[] args) throws Exception {
        CountDownLatch doneSignal = new CountDownLatch(5);
        ExecutorService service = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 5; ++i) // create and start threads
            service.execute(new WorkerRunnable(doneSignal, i));
        System.out.println("await before");
        doneSignal.await();
        System.out.println("await after");
        service.shutdown();
    }

    private static class WorkerRunnable implements Runnable {
        private final CountDownLatch doneSignal;
        private final int i;

        public WorkerRunnable(CountDownLatch doneSignal, int i) {
            this.doneSignal = doneSignal;
            this.i = i;
        }

        @Override
        public void run() {
            doWork(i);
            try {
                Thread.sleep(new Random().nextInt(1000));
                doneSignal.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        private void doWork(int i) {
            System.out.println("in run method: " + i + " " + Thread.currentThread().getName());
        }
    }
}
